package org.orz.cloud.auth;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
        if(!(attributes instanceof ServletRequestAttributes)){
            return;
        }

        HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();
        template.header(AuthConstants.HEADER_WORKBENCH, request.getHeader(AuthConstants.HEADER_WORKBENCH))
                .header(AuthConstants.HEADER_AUTHORIZATION, request.getHeader(AuthConstants.HEADER_AUTHORIZATION));
    }
}
